package com.wizz.trade.trading.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wizz.trade.common.PageVo;
import com.wizz.trade.common.ResponseResult;
import com.wizz.trade.common.ServiceException;
import com.wizz.trade.common.constant.StatusCode;
import com.wizz.trade.information.mapper.*;
import com.wizz.trade.trading.controller.TradeThirdController;
import com.wizz.trade.trading.dto.page.TradePageDto;
import com.wizz.trade.trading.entity.Cons;
import com.wizz.trade.trading.entity.Position;
import com.wizz.trade.trading.entity.Trade;
import com.wizz.trade.trading.mapper.PositionMapper;
import com.wizz.trade.trading.mapper.TradeMapper;
import com.wizz.trade.trading.service.TradeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wizz.trade.trading.vo.TradeForFirstPageVo;
import com.wizz.trade.trading.vo.TradeForSecondPageVo;
import com.wizz.trade.trading.vo.TradeForThirdPageVo;
import com.wizz.trade.util.FileOperationUtil;
import com.wizz.trade.util.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 贸易表 服务实现类
 * </p>
 *
 * @author fyftless
 * @since 2023-04-23 04:37:04
 */
@Service
public class TradeServiceImpl extends ServiceImpl<TradeMapper, Trade> implements TradeService {

    @Resource
    private TradeMapper tradeMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private CompanydeptMapper companydeptMapper;

    @Resource
    private VarietyMapper varietyMapper;

    @Resource
    private GradeMapper gradeMapper;

    @Resource
    private TrademarkMapper trademarkMapper;

    @Resource
    private CurrencyMapper currencyMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private FileOperationUtil fileOperationUtil;

    @Override
    public void addTrade(Trade trade) {
        tradeMapper.insert(trade);
    }

    @Override
    public void updateTrade(Trade trade) {
        tradeMapper.updateById(trade);
    }

    @Override
    public void deleteTrade(Integer id) {
        tradeMapper.deleteById(id);
    }

    @Override
    public PageVo<TradeForFirstPageVo> getPageForFirstPage(TradePageDto tradePageDto) {
        IPage<Trade> page = getRawPageRecords(tradePageDto);
        List<Trade> records = page.getRecords();
        List<TradeForFirstPageVo> tradeVos = new ArrayList<>();
        for (Trade item : records) {
            TradeForFirstPageVo vo = new TradeForFirstPageVo();
            vo.setId(item.getId());
            vo.setDate(item.getDate());
            vo.setLedger(companyMapper.selectById(item.getLedgerId()).getShortname());
            vo.setOurDept(companydeptMapper.selectById(item.getOurDeptId()).getName());
            vo.setCompany(companyMapper.selectById(item.getCompanyId()).getShortname());
            vo.setCompanyDept(companydeptMapper.selectById(item.getCompanyDeptId()).getName());
            vo.setPs(item.getPs());
            vo.setVariety(varietyMapper.selectById(item.getVarietyId()).getName());
            vo.setGrade(gradeMapper.selectById(item.getGradeId()).getName());
            vo.setTrademark(trademarkMapper.selectById(item.getTrademarkId()).getName());
            vo.setReal(item.getRealqty());
            //TODO unit需要修改
            vo.setUnit(varietyMapper.selectById(item.getVarietyId()).getUnit());
            vo.setAtPrice(item.getAtPrice());
            vo.setCurrency(currencyMapper.selectById(item.getCurrencyId()).getName());
            vo.setPattern(item.getPattern());
            vo.setOrder(ordersMapper.selectById(item.getOrderId()).getMode());
            vo.setDeliver(item.getDeliver());
            vo.setBatchNo(item.getBatchNo());
            vo.setOrderNo(item.getOrderNo());
            tradeVos.add(vo);
        }
        return new PageVo<>(page.getPages(), page.getTotal(), tradeVos);
    }

    @Override
    public PageVo<TradeForSecondPageVo> getPageForSecondPage(TradePageDto tradePageDto) {
        IPage<Trade> page = getRawPageRecords(tradePageDto);
        List<Trade> records = page.getRecords();
        List<TradeForSecondPageVo> tradeVos = new ArrayList<>();
        for (Trade item : records) {
            TradeForSecondPageVo vo = new TradeForSecondPageVo();
            vo.setId(item.getId());
            vo.setDate(item.getDate());
            vo.setGenState(item.getGenState());
            vo.setLedger(companyMapper.selectById(item.getLedgerId()).getShortname());
            vo.setOurDept(companydeptMapper.selectById(item.getOurDeptId()).getName());
            vo.setCompany(companyMapper.selectById(item.getCompanyId()).getShortname());
            vo.setPs(item.getPs());
            vo.setVariety(varietyMapper.selectById(item.getVarietyId()).getName());
            vo.setGrade(gradeMapper.selectById(item.getGradeId()).getName());
            vo.setTrademark(trademarkMapper.selectById(item.getTrademarkId()).getName());
            vo.setReal(item.getRealqty());
            //TODO unit需要修改
            vo.setUnit(varietyMapper.selectById(item.getVarietyId()).getUnit());
            vo.setAtPrice(item.getAtPrice());
            vo.setCurrency(currencyMapper.selectById(item.getCurrencyId()).getName());
            vo.setAmount(item.getAmount());
            vo.setPattern(item.getPattern());
            vo.setOrder(ordersMapper.selectById(item.getOrderId()).getMode());
            vo.setDeliver(item.getDeliver());
            vo.setOrderNo(item.getOrderNo());
            tradeVos.add(vo);
        }
        return new PageVo<>(page.getPages(), page.getTotal(), tradeVos);
    }

    @Override
    public PageVo<TradeForThirdPageVo> getPageForThirdPage(TradePageDto tradePageDto) {
        IPage<Trade> page = getRawPageRecords(tradePageDto);
        List<Trade> records = page.getRecords();
        List<TradeForThirdPageVo> tradeVos = new ArrayList<>();
        for (Trade item : records) {
            TradeForThirdPageVo vo = new TradeForThirdPageVo();
            vo.setId(item.getId());
            vo.setDate(item.getDate());
            vo.setLedger(companyMapper.selectById(item.getLedgerId()).getShortname());
            vo.setOurDept(companydeptMapper.selectById(item.getOurDeptId()).getName());
            vo.setCompany(companyMapper.selectById(item.getCompanyId()).getShortname());
            vo.setCompanyDept(companydeptMapper.selectById(item.getCompanyDeptId()).getName());
            vo.setReqState(item.getReqState());
            //TODO 签订状态specialState后期需要修改
            vo.setSpecialState(null);
            vo.setVariety(varietyMapper.selectById(item.getVarietyId()).getName());
            vo.setGrade(gradeMapper.selectById(item.getGradeId()).getName());
            vo.setTrademark(trademarkMapper.selectById(item.getTrademarkId()).getName());
            vo.setReal(item.getRealqty());
            //TODO unit需要修改
            vo.setUnit(varietyMapper.selectById(item.getVarietyId()).getUnit());
            vo.setAtPrice(item.getAtPrice());
            vo.setCurrency(currencyMapper.selectById(item.getCurrencyId()).getName());
            vo.setAmount(item.getAmount());
            vo.setActAmount(item.getActAmount());
            vo.setPattern(item.getPattern());
            vo.setOrder(ordersMapper.selectById(item.getOrderId()).getMode());
            vo.setDeliver(item.getDeliver());
            vo.setOrderNo(item.getOrderNo());
            vo.setContractno(item.getContractNo());
            tradeVos.add(vo);
        }
        return new PageVo<>(page.getPages(), page.getTotal(), tradeVos);
    }

    @Override
    public List<Trade> getAll() {
        return null;
    }

    @Override
    public void sale(Trade trade, List<Position> positions) {
        tradeMapper.insert(trade);
        for (Position p : positions) {
            if (p.getOi().compareTo(BigDecimal.ZERO) <= 0) {
                throw new ServiceException("数据非法");
            }
            Position position = positionMapper.selectById(p.getId());
            position.setOi(p.getOi());
            position.setStorageCapital(position.getCprice().multiply(position.getOi()));
            if(Objects.nonNull(position.getSprice())){
                position.setFpl((position.getSprice().subtract(position.getCprice())).
                        multiply(position.getOi()));
            }
            positionMapper.updateById(position);
        }
    }

    @Override
    public String uploadTradeImage(Integer id, MultipartFile multipartFile) {
        String url = fileOperationUtil.uploadImage(multipartFile);
        Trade trade = tradeMapper.selectById(id);
        trade.setScan(url);
        tradeMapper.updateById(trade);
        return url;
    }

    private IPage<Trade> getRawPageRecords(TradePageDto tradePageDto){
        LambdaQueryWrapper<Trade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!Objects.isNull(tradePageDto.getPs()), Trade::getPs, tradePageDto.getPs());
        queryWrapper.eq(Objects.nonNull(tradePageDto.getDate()),Trade::getDate, tradePageDto.getDate());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getLedgerId()),Trade::getLedgerId, tradePageDto.getLedgerId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getOurDeptId()), Trade::getOurDeptId,tradePageDto.getOurDeptId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getCompanyId()),Trade::getCompanyId,tradePageDto.getCompanyId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getCompanyDeptId()), Trade::getCompanyDeptId, tradePageDto.getCompanyDeptId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getGradeId()), Trade::getGradeId, tradePageDto.getGradeId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getVarietyId()), Trade::getVarietyId, tradePageDto.getVarietyId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getTrademarkId()), Trade::getTrademarkId, tradePageDto.getTrademarkId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getOrderId()), Trade::getOrderId, tradePageDto.getOrderId());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getPattern()), Trade::getPattern, tradePageDto.getPattern());
        queryWrapper.eq(!Objects.isNull(tradePageDto.getDeliver()), Trade::getDeliver, tradePageDto.getDeliver());
        queryWrapper.likeRight(StringUtils.isNotBlank(tradePageDto.getOrderNo()), Trade::getOrderId, tradePageDto.getOrderNo());
        IPage<Trade> page = tradeMapper.selectPage(PageUtil.initPage(tradePageDto), queryWrapper);
        return page;
    }

}
